package com.cyk.like_test.handler;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.cyk.like_test.model.constants.MqConst;
import com.cyk.like_test.model.entity.AlbumLike;
import com.cyk.like_test.model.entity.AlbumStat;
import com.cyk.like_test.model.msg.LikeMsg;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
public class MqHandler {

    @Resource
    private ObjectMapper objectMapper;

    @SneakyThrows
    @RabbitListener(queues = MqConst.LIKE_MySQL_QUEUE)
    public void updateMySQLLikeStat(String jsonMsg) {
        LikeMsg msg = objectMapper.readValue(jsonMsg, LikeMsg.class);
        String ans = msg.getIsLike() ? "+ 1" : "- 1";
        Db.lambdaUpdate(AlbumStat.class)
                .setSql("like_cnt = like_cnt " + ans)
                .eq(AlbumStat::getAlbumId, msg.getTargetId())
                .update();
    }

    @SneakyThrows
    @RabbitListener(queues = MqConst.SYNC_LIKE_MYSQL_QUEUE)
    public void syncLikeData(String jsonMsg) {
        LikeMsg msg = objectMapper.readValue(jsonMsg, LikeMsg.class);
        if(msg.getIsLike()) {
            //1.添加点赞信息
            Db.save(
                    AlbumLike.builder()
                            .postId(msg.getPostId())
                            .targetId(msg.getTargetId())
                            .ctTime(new Date())
                            .utTime(new Date())
                            .build()
            );
            //2.更新点赞量
            Db.lambdaUpdate(AlbumStat.class)
                    .setSql("like_cnt = like_cnt + 1")
                    .eq(AlbumStat::getAlbumId, msg.getTargetId())
                    .update();
        } else {
            Db.lambdaUpdate(AlbumLike.class)
                    .eq(AlbumLike::getPostId, msg.getPostId())
                    .eq(AlbumLike::getTargetId, msg.getTargetId())
                    .remove();
            Db.lambdaUpdate(AlbumStat.class)
                    .setSql("like_cnt = like_cnt - 1")
                    .eq(AlbumStat::getAlbumId, msg.getTargetId())
                    .update();
        }
    }


}
